public class Solution222 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int countNodes(TreeNode root) {
        if (root==null){
            return 0;
        }
        return dfs(root,1);
    }

    public int dfs(TreeNode root,int cur){
        if (root.left==null && root.right==null){
            return cur;
        }
        int ans=dfs(root.left,cur*2);
        if (root.right!=null){
            ans=Math.max(ans,dfs(root.right,cur*2+1));
        }
        return ans;
    }


    public static void main(String[] args) {
        System.out.println(new Solution222().countNodes(new TreeNode(1,new TreeNode(2,new TreeNode(4),new TreeNode(5)),new TreeNode(3,new TreeNode(6),null))));
    }
}
